import network
import json
import time

with open('../kernel/config/netconf.json') as config:
    cfg = json.load(config)

if cfg["host"]:
    try:
        ap = network.WLAN(network.AP_IF)  # create access-point interface
        ap.config(ssid=cfg["SSID"], )  # set the SSID of the access point
        ap.config(max_clients=cfg["maxclients"])  # set how many clients can connect to the network
        ap.active(True)  # activate the interface
    except:
        pass
else:
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect(cfg["SSID"], cfg["Password"])
        start_time = time.time()
        while not wlan.isconnected():
            if time.time() - start_time > 30:  # Если прошло более 30 секунд
                ap = network.WLAN(network.AP_IF)  # создаем точку доступа
                ap.config(ssid=cfg["SSID"], authmode=network.AUTH_WPA_WPA2_PSK, password=cfg["Password"])
                ap.active(True)
                break
            time.sleep(1)
